package com.example.iceserverdemo.meeting.services;

import com.example.iceserverdemo.meeting.models.MeetingRoom;
import com.example.iceserverdemo.utils.MapUtil;
import com.example.iceserverdemo.utils.RandomUtil;

import javax.websocket.Session;
import java.util.*;

public class MeetingService {
    private static Map<String, Session> sessions = new HashMap<>();

    public static void addSession(Session session) {
        sessions.put(session.getId(), session);
    }

    public static void removeSession(Session session) {
        sessions.remove(session.getId());
    }

    public static boolean containsSession(String id) {
        return sessions.containsKey(id);
    }

    public static Set<String> getSessions() {
        return sessions.keySet();
    }

    public static void sendMessageTo(Session target, String data) throws Exception {
        synchronized (target) {
            if (target.isOpen())
                target.getBasicRemote().sendText(data);
        }
    }

    public static void sendMessageTo(String target, String data) throws Exception {
        if (containsSession(target))
            sendMessageTo(sessions.get(target), data);
    }

    public static void sendMessageTo(String[] targets, String data) throws Exception {
        for (String target : targets)
            sendMessageTo(target, data);
    }

    public static void sendMessageExcept(Session except, String data) throws Exception {
        for (Session session : sessions.values()) {
            if (session != except)
                sendMessageTo(session, data);
        }
    }

    public static String getNewRoomNumber() {
        return (RandomUtil.get(100000000) + 100000000) + "";
    }

    private static Map<String, MeetingRoom> rooms = new LinkedHashMap();

    public static void addRoom(MeetingRoom room) {
        rooms.put(room.number, room);
    }

    public static void removeRoom(String number) {
        rooms.remove(number);
    }

    public static void clearRooms() {
        rooms.clear();
    }

    public static boolean containsRoom(String number) {
        return rooms.containsKey(number);
    }

    public static MeetingRoom getRoom(String number) {
        return rooms.get(number);
    }

    public static MeetingRoom getRoomByMaster(String master) {
        for (MeetingRoom room : rooms.values()) {
            if (room.master.equals(master))
                return room;
        }
        return null;
    }

    public static ArrayList<MeetingRoom> getAllRooms() {
        return MapUtil.getReverseValues(rooms);
    }
}
